package com.one.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.one.bo.SelectUserBo;
import com.one.bo.UserBo;
import com.one.bo.UserLoginBo;
import com.one.dto.PaginationDate;
import com.one.dto.ReturnDate;
import com.one.dto.User;
import com.one.entity.SysUserEntity;
import com.one.entity.UserRoleEntity;
import com.one.enums.IsDeletedEnum;
import com.one.enums.SexEnum;
import com.one.enums.StatusEnum;
import com.one.mapper.SysRoleMapper;
import com.one.mapper.SysUserMapper;
import com.one.mapper.UserRoleMapper;
import com.one.service.SysUserService;
import com.one.utils.DataCheckUtils;
import com.one.utils.DateUtils;
import com.one.utils.PaginationUtils;
import com.one.utils.TokenUtils;
import com.one.dto.Result;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zwj
 * @since 2021-09-08
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {
    private final SysUserMapper sysUserMapper;
    private final UserRoleMapper userRoleMapper;
    public SysUserServiceImpl(SysUserMapper sysUserMapper,UserRoleMapper userRoleMapper) {
        this.sysUserMapper = sysUserMapper;
        this.userRoleMapper = userRoleMapper;
    }
    //登录
    @Override
    public Result login(UserLoginBo userLoginBo) {

        //数据校验
        DataCheckUtils.isNotBlank(userLoginBo.getAccount(), "用户账号不能为空!");
        DataCheckUtils.isNotBlank(userLoginBo.getPassword(), "密码不能为空!");
//        DataCheckUtils.isNotBlank(userLoginBo.getCode(), "验证码不能为空!");
        //以用户类型与账号查询用户信息
        QueryWrapper<SysUserEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(SysUserEntity::getAccount, userLoginBo.getAccount()).eq(SysUserEntity::getIsDeleted, IsDeletedEnum.NO.getKey())
                .select(SysUserEntity::getStatus,SysUserEntity::getPassword,SysUserEntity::getId,SysUserEntity::getName);
        SysUserEntity user = sysUserMapper.selectOne(sectionQueryWrapper);
        //查询结果校验
        if (user == null) {
            return Result.error().message("账号不存在！");
        }
        if (StatusEnum.INVALID.getKey().equals(user.getStatus())) {
            return Result.error().message("用户已停用！");
        }
        //md5加密
        if(!user.getPassword().equals(DigestUtils.md5DigestAsHex(userLoginBo.getPassword().getBytes(StandardCharsets.UTF_8)))){
            return Result.error().message("用户密码错误！");
        }
        //生成token
        String token = TokenUtils.getJwtToken(user.getId().toString());

        return Result.ok().data(new User(null,token,user.getName(),null,null));
    }
    //条件查询用户
    @Override
    public Result selectUser(SelectUserBo selectUserBo) {

        //数据校验
        DataCheckUtils.isValid(PaginationUtils.isPagingParameters(selectUserBo.getNumber(), selectUserBo.getPage()), "分页参数错误!");
        int page = selectUserBo.getPage();
        selectUserBo.setPage(PaginationUtils.getPageIndex(selectUserBo.getPage(), selectUserBo.getNumber()));
        //查询项目组评分 mybatis
        List<Object> result = sysUserMapper.selectUser(selectUserBo);
        int sum = ((List<Integer>) result.get(1)).get(0);
        //记录总数为0
        if (sum == 0) return Result.error().message("查询结果为空");
        PaginationDate paginationDate = PaginationUtils.getPaginationDate(selectUserBo.getNumber(), page, sum);
        //当前页大于总页数
        if (PaginationUtils.isValid(paginationDate))
            return Result.error().message("分页参数错误!");
        List<SysUserEntity> sysUserEntities =  (List<SysUserEntity>) result.get(0);
        for (SysUserEntity sysUserEntity:sysUserEntities){
            sysUserEntity.setSex(SexEnum.getEnumValue(sysUserEntity.getSex()));
        }
        return Result.ok().data(new ReturnDate(paginationDate,sysUserEntities ));
    }

    @Override
    public Result updateUserStatus(UserBo userBo) {
        //数据校验
        DataCheckUtils.isNotBlank(userBo.getId(), "用户Id不能为空!");
        DataCheckUtils.isNotBlank(userBo.getStatus(), "用户状态不能为空!");
        DataCheckUtils.isValid(StatusEnum.getEnumValue(userBo.getStatus()) != null, "用户状态不存在");
        QueryWrapper<SysUserEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(SysUserEntity::getId, userBo.getId()).eq(SysUserEntity::getIsDeleted, IsDeletedEnum.NO.getKey()).select(SysUserEntity::getStatus);
        SysUserEntity user = sysUserMapper.selectOne(sectionQueryWrapper);
        //查询结果校验
        if (user == null) {
            return Result.error().message("账号不存在！");
        }
        if (userBo.equals(user.getStatus())) {
            return Result.error().message("用户状态不匹配不能修改");
        }
        SysUserEntity updateStatus = new SysUserEntity();
        updateStatus.setStatus(userBo.getStatus());
        UpdateWrapper<SysUserEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(SysUserEntity::getId, userBo.getId());
        int row = sysUserMapper.update(updateStatus, updateWrapper);
        //判断修改结果
        if (row == 0) {
            return Result.error().message("编辑用户状态失败");
        }
        return Result.ok();
    }

    @Override
    public Result deleteUser(UserBo userBo) {
        DataCheckUtils.isNotBlank(userBo.getId(), "用户id不能为空!");
        QueryWrapper<SysUserEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(SysUserEntity::getId, userBo.getId()).eq(SysUserEntity::getIsDeleted, IsDeletedEnum.NO.getKey()).select(SysUserEntity::getStatus,SysUserEntity::getPassword,SysUserEntity::getId,SysUserEntity::getName);;
        SysUserEntity user = sysUserMapper.selectOne(sectionQueryWrapper);
        //查询结果校验
        if (user == null) {
            return Result.error().message("账号不存在！");
        }
        SysUserEntity sysUserEntity = new SysUserEntity();
        sysUserEntity.setIsDeleted(IsDeletedEnum.YES.getKey());
        UpdateWrapper<SysUserEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(SysUserEntity::getId, userBo.getId()).eq(SysUserEntity::getIsDeleted,IsDeletedEnum.NO.getKey());
        int row = sysUserMapper.update(sysUserEntity, updateWrapper);
        //判断修改结果
        if (row == 0) {
            return Result.error().message("删除用户失败");
        }
        return Result.ok();
    }

    @Override
    public Result addUser(SysUserEntity sysUserEntity) {
        //数据校验
        DataCheckUtils.isNotBlank(sysUserEntity.getName(), "教师姓名不能为空!");
        //查询指定工号、身份证号、手机号是否重复
        //插入数据
        String role = sysUserEntity.getRole();
        sysUserEntity.setRole(null);
        sysUserEntity.setIsDeleted("0");
        sysUserEntity.setCreateBy("1");
        sysUserEntity.setCreateTime(DateUtils.getCurrentTime());
        sysUserEntity.setPassword(DigestUtils.md5DigestAsHex("666666".getBytes(StandardCharsets.UTF_8)));
        //判断插入结果
        if (SqlHelper.retBool(sysUserMapper.insert(sysUserEntity))==false) {
            return Result.error().message("添加用户失败");
        }
        UserRoleEntity userRoleEntity = new UserRoleEntity();
        userRoleEntity.setRoleId(role);
        userRoleEntity.setUserId(sysUserEntity.getId());
        int result = userRoleMapper.insert(userRoleEntity);
        //记录总数为0
        if (result == 0) return Result.error().message("添加用户失败");
        return Result.ok();
    }

    @Override
    public Result updateUser(SysUserEntity sysUserEntity) {
        String role = sysUserEntity.getRole();
        sysUserEntity.setRole(null);
        UpdateWrapper<SysUserEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(SysUserEntity::getId, sysUserEntity.getId());
        int row = sysUserMapper.update(sysUserEntity, updateWrapper);
        //判断修改结果
        if (row == 0) {
            return Result.error().message("编辑用户信息");
        }
        return Result.ok();
    }
    //学院负责人
    @Override
    public Result updateCollegeLeading(SysUserEntity sysUserEntity) {
        DataCheckUtils.isNotBlank(sysUserEntity.getId(), "用户Id不能为空!");
        DataCheckUtils.isNotBlank(sysUserEntity.getIscollegeleading(), "负责人不能为空!");
        QueryWrapper<SysUserEntity> updateCollegeLeading = new QueryWrapper<>();
        updateCollegeLeading.lambda().eq(SysUserEntity::getId,sysUserEntity.getId());
        int row=sysUserMapper.update(sysUserEntity,updateCollegeLeading);
        if (row == 0) {
            return Result.error().message("操作失败");
        }
        return Result.ok();
    }
}
